<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;

class Chuchai extends Commonwork
{   
  //打回修改处理
  public function baocunchuli(){
      $request = Request::instance();$data = $request->post();
      $adddata["state"]=3;$aid=$data["aid"];$fid=5;
      $adddata["traveltype"]=$data["traveltype"];
          if(isset($data["baifang"]))
              $adddata["baifang"]=implode(',', $data["baifang"]);
          if($data["dailiren"])
              $adddata["dailiren"]=$data["dailiren"];
          if(trim($data["title"]))
              $adddata["title"]=$data["title"];
          else
              return json_encode(["msg"=>"主题不能为空","state"=>2]);
          if(trim($data["feiyong"]))
              $adddata["feiyong"]=trim($data["feiyong"]);
          else
              $adddata["feiyong"]=0;
          if(strip_tags(trim($data["target"])))
              $adddata["target"]=trim($data["target"]);
          else
              return json_encode(["msg"=>"行程目的不能为空","state"=>2]);
          $adddata["fujian"]=$data["attach"];
          $adddetail=[];
          $reg_time="/^\d{2}:\d{2}$/";
          if(isset($data["start"])&&isset($data["end"])&&isset($data["chufa"])){
              for($i=0;$i<count($data["start"]);$i++){
                  $tmp=[];
                  $tmp["aid"]=$aid;
                  if($data["start"][$i])
                      $tmp["start"]=$data["start"][$i];
                  else{
                      Db::rollBack();
                      if(!$data["aid"]){
                          Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                      }
                  return json_encode(["msg"=>"明细起始时间不能为空","state"=>2]);
              }
              if($data["end"][$i])
                  $tmp["end"]=$data["end"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细终止时间不能为空","state"=>2]);
              }
              if($data["chufa"][$i])
                  $tmp["chufa"]=$data["chufa"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细出发地不能为空","state"=>2]);
              }
              if($data["mudi"][$i])
                  $tmp["mudi"]=$data["mudi"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细目的地不能为空","state"=>2]);
              }
              if($data["ts"][$i])
                  $tmp["ts"]=$data["ts"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细天数不能为空或0","state"=>2]);
              }
              if($data["gl"][$i])
                  $tmp["gl"]=$data["gl"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细点对点公里数不能为空或0","state"=>2]);
              }
              if(preg_match($reg_time,trim($data["qishi"][$i])))
                  $tmp["qishi"]=trim($data["qishi"][$i]);
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                  return json_encode(["msg"=>"明细发车/起飞时间请按正确格式如：09:30","state"=>2]);
              }
              $tmp["fangshi"]=$data["fangshi"][$i];
              if($data["shijian"][$i])
                  $tmp["shijian"]=$data["shijian"][$i];
              else{
                  Db::rollBack();
                  if(!$data["aid"]){
                      Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
                  }
                return json_encode(["msg"=>"明细点对点乘车小时不能为空或0","state"=>2]);
              }
              if($data["peitongid"][$i])
                  $tmp["peitongid"]=$data["peitongid"][$i];
              else
                  $tmp["peitongid"]=null;
              if($data["peitongren"][$i])
                  $tmp["peitongren"]=$data["peitongren"][$i];
              else
                  $tmp["peitongren"]=null;
              $adddetail[]=$tmp;
          }
      }else{
            
          return json_encode(["msg"=>"请至少添加一条明细","state"=>2]);
         
      }
          $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
          if($res["operateStatus"]=="success"){
              Db::startTrans();
      
              try{
                     //修改
                  $adddata["puser"]=Session::get("employee_id");
                  $adddata["ptime"]=time();
                  $res1=Db::table("chuchai_apply")->where(["id"=>$aid])->update($adddata);
                  
                  Db::table("chuchai_detail")->where(["aid"=>$aid])->delete();
                  $res2=Db::table("chuchai_detail")->insertAll($adddetail);
              }catch (\Exception $e){
                  Db::rollBack();
                  return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
              }
              if($res1&&$res2){
                  Db::commit();
                  return json_encode(["msg"=>"","state"=>1]);
              }else{
                  Db::rollBack();
                  return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
              }

          }else{
              return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
          }
          
         
       
        
    }
    //作废处理
    public function zuofeichuli(){
      $request = Request::instance();$data = $request->post();
      //print_r($data);exit;
      $fid=5;$aid=$data["aid"];$reason=$data["reason"];
      if(!trim($reason))
        return json_encode(["msg"=>"作废原因不能为空","state"=>2]);
      $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
      if($res["operateStatus"]=="success"){
        $up["feiuser"]=Session::get("employee_id");
        $up["feitime"]=time();
        $up["feireason"]=$reason;
        $up["id"]=$aid;
        $up["state"]=8;
        try{
          Db::table("chuchai_apply")->update($up);
        }catch (\Exception $e){
        
          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
      return json_encode(["msg"=>"","state"=>1]);
        
      }else{
        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
      }
      
    }
    //作废页面
    public function zuofei($aid,$from=1){
      $this->assign("from",$from);
      $this->assign("aid",$aid);
      $apply=Db::table("chuchai_apply")->where("id=$aid")->find();
      $this->assign("apply",$apply);
      $eid=$apply["cuser"];
      $ctime=date("Y-m-d H:i:s",$apply["ctime"]);

      $fujian=[];
      //print_r($apply);
      if($apply["fujian"]){
        $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
        //print_r($fujian);
      }
      $daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
      $this->assign("daili",$daili);
            $state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

            $de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
            $this->assign("de",$de);
            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("ctime",$ctime);
        $this->assign("state",$state);
        $logs=$this->getlog(5,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
        $btn=$this->getbton(5,$aid);
        $this->assign("btn",$btn);
        //print_r($btn);
    return $this->fetch();
  }
    //审核页面
    public function shenhe($myId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
        $apply=Db::table("chuchai_apply")->where("id=$aid")->find();
        $state=$apply["state"];
        if($state==2){
          $this->redirect('Chuchai/zuofei', ['aid' => $aid,"from"=>2]);
        }else{
          $this->assign("apply",$apply);
            $eid=$apply["cuser"];
            $ctime=date("Y-m-d H:i:s",$apply["ctime"]);

            $fujian=[];
            //print_r($apply);
            if($apply["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                //print_r($fujian);
            }
            $daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
            $this->assign("daili",$daili);
            $state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

            $de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
            $this->assign("de",$de);
            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
            $this->assign("user",$user);
            $this->assign("fujian",$fujian);
            $this->assign("ctime",$ctime);
            $this->assign("state",$state);
            $logs=$this->getlog(5,$aid);
            //print_r($logs);
            $this->assign("logs",$logs);
            return $this->fetch();
        }
            
    }
	public function daochu($aid){
		$apply=Db::table("chuchai_apply")->where("id=$aid")->find();
			
			if($apply["baifang"]=="1,2")
				$baifang="经销客户,直营客户";
			else if($apply["baifang"]=="1")
				$baifang="经销客户";
			else if($apply["baifang"]=="2")
				$baifang="直营客户";
			else
				$baifang="";
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);

			
			$daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
			$dailiren="无";
			if($daili)
				$dailiren=$daili["em_name"];
			
          	$state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

          	$de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
          	
          	$user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
            $logs=$this->getlog(5,$aid);
        	$eid=Session::get("employee_id");
    		$users=Db::table("employee")->where(["id"=>$eid])->find();
	  Vendor("PHPExcel");
        
        
       Vendor("PHPExcel.Writer.Excel5");

       // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
       //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel= new PHPExcel();
            
            
        $objProps=$objPHPExcel->getProperties();
            
        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");
            	
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("出差申请导出");
              #标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
 

       

        
          $objPHPExcel->getActiveSheet()->mergeCells('A1:J1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "出差申请详情");
              //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);

            #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:J2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2',"(本表单由软件导出，导出时间：".date("Y-m-d H:i:s")."；导出人：{$users["em_name"]})");
                //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);

        $objPHPExcel->getActiveSheet()->setCellValue('A3',"类型");
        $objPHPExcel->getActiveSheet()->mergeCells('B3:J3');
        if($apply["traveltype"]==1)
        	$objPHPExcel->getActiveSheet()->setCellValue('B3',"周边行程");
        else
        	$objPHPExcel->getActiveSheet()->setCellValue('B3',"出差申请");

         $objPHPExcel->getActiveSheet()->setCellValue('A4',"编号");
         $objPHPExcel->getActiveSheet()->mergeCells('B4:F4');
         $objPHPExcel->getActiveSheet()->setCellValue('B4',$apply["no"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('G4',"申请时间");
         $objPHPExcel->getActiveSheet()->mergeCells('H4:J4');
         $objPHPExcel->getActiveSheet()->setCellValue('H4',date("Y-m-d H:i:s",$apply["ctime"]),PHPExcel_Cell_DataType::TYPE_STRING);

         $objPHPExcel->getActiveSheet()->setCellValue('A5',"部门");
         $objPHPExcel->getActiveSheet()->mergeCells('B5:F5');
         $objPHPExcel->getActiveSheet()->setCellValue('B5',$user["de_name"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('G5',"状态");
         $objPHPExcel->getActiveSheet()->mergeCells('H5:J5');
         $objPHPExcel->getActiveSheet()->setCellValue('H5',$state,PHPExcel_Cell_DataType::TYPE_STRING);

         $objPHPExcel->getActiveSheet()->setCellValue('A6',"姓名");
         $objPHPExcel->getActiveSheet()->mergeCells('B6:F6');
         $objPHPExcel->getActiveSheet()->setCellValue('B6',$user["em_name"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('G6',"职务");
         $objPHPExcel->getActiveSheet()->mergeCells('H6:J6');
         $objPHPExcel->getActiveSheet()->setCellValue('H6',$user["role_name"],PHPExcel_Cell_DataType::TYPE_STRING);

          $objPHPExcel->getActiveSheet()->setCellValue('A7',"拜访客户");
         $objPHPExcel->getActiveSheet()->mergeCells('B7:F7');
         $objPHPExcel->getActiveSheet()->setCellValue('B7',$baifang,PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('G7',"职务代理人");
         $objPHPExcel->getActiveSheet()->mergeCells('H7:J7');
         $objPHPExcel->getActiveSheet()->setCellValue('H7',$dailiren,PHPExcel_Cell_DataType::TYPE_STRING);

          $objPHPExcel->getActiveSheet()->setCellValue('A8',"主题");
         $objPHPExcel->getActiveSheet()->mergeCells('B8:F8');
         $objPHPExcel->getActiveSheet()->setCellValue('B8',$apply["title"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('G8',"预估差旅费用");
         $objPHPExcel->getActiveSheet()->mergeCells('H8:J8');
         $objPHPExcel->getActiveSheet()->setCellValue('H8',$apply["feiyong"],PHPExcel_Cell_DataType::TYPE_STRING);
                //水平剧中
       // $objPHPExcel->getActiveSheet()->getStyle('A3:J8')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A3:J8')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

          $objPHPExcel->getActiveSheet()->getStyle('9')->getAlignment()->setWrapText(true);
	    
	     $objPHPExcel->getActiveSheet()->getStyle('A9:J9')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
	     $objPHPExcel->getActiveSheet()->getStyle('A9:J9')->getFill()->getStartColor()->setARGB('0099CCFF');
	         //水平剧中
	     $objPHPExcel->getActiveSheet()->getStyle('A9:J9')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	        //垂直剧中
	     $objPHPExcel->getActiveSheet()->getStyle('A9:J9')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

	    $objPHPExcel->getActiveSheet()->setCellValue('A9',"起始时间");
        $objPHPExcel->getActiveSheet()->setCellValue('B9',"结束时间");
        $objPHPExcel->getActiveSheet()->setCellValue('C9',"出发地");
        $objPHPExcel->getActiveSheet()->setCellValue('D9',"目的地");
        $objPHPExcel->getActiveSheet()->setCellValue('E9',"天数");      
        $objPHPExcel->getActiveSheet()->setCellValue('F9',"点对点公里数");
        $objPHPExcel->getActiveSheet()->setCellValue('G9',"发车/起飞时间  时：分,如：09：30");
        $objPHPExcel->getActiveSheet()->setCellValue('H9',"交通工具");
        $objPHPExcel->getActiveSheet()->setCellValue('I9',"点对点乘车  所需时间(小时)");
        $objPHPExcel->getActiveSheet()->setCellValue('J9',"陪同人员");

        $h=9;
        for($i=0;$i<count($de);$i++){
        	$h++;$vo=$de[$i];
        	$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$vo["start"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('B'.$h,$vo["end"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('C'.$h,$vo["chufa"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('D'.$h,$vo["mudi"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('E'.$h,$vo["ts"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('F'.$h,$vo["gl"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('G'.$h,$vo["qishi"],PHPExcel_Cell_DataType::TYPE_STRING);
        	switch ($vo["fangshi"]) {
        		case 0:$fs="火车";break;
        		case 0:$fs="轮渡";break;
        		case 0:$fs="飞机";break;
        		case 0:$fs="大巴";break;
        		case 0:$fs="自驾车";break;
        		default:
        			$fs="其他";
        			break;
        	}

        	$objPHPExcel->getActiveSheet()->setCellValue('H'.$h,$fs,PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('I'.$h,$vo["shijian"],PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('J'.$h,$vo["peitongren"],PHPExcel_Cell_DataType::TYPE_STRING);
        }

         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
           $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
           $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
           $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
           $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
           $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);

            $h++;
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"行程目的\n(需要解决的问题)");
	        $objPHPExcel->getActiveSheet()->mergeCells("B{$h}:J{$h}");
	        $objPHPExcel->getActiveSheet()->setCellValue('B'.$h,strip_tags($apply["target"]),PHPExcel_Cell_DataType::TYPE_STRING);

	        $h++;
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"反馈信息");
	        $objPHPExcel->getActiveSheet()->mergeCells("B{$h}:J{$h}");
	        if($apply["fankui"])
	        	$objPHPExcel->getActiveSheet()->setCellValue('B'.$h,strip_tags($apply["fankui"]),PHPExcel_Cell_DataType::TYPE_STRING);
	        else
	        	$objPHPExcel->getActiveSheet()->setCellValue('B'.$h,"未反馈",PHPExcel_Cell_DataType::TYPE_STRING);

	        $h++;$h++;
	        $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"审批意见");
	        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:J{$h}");
	         $objPHPExcel->getActiveSheet()->getStyle("A{$h}:J{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
	     $objPHPExcel->getActiveSheet()->getStyle("A{$h}:J{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');

            for($i=0;$i<count($logs);$i++){
                $h++;
                if($logs[$i]["COMMENTS"])
                    $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：{$logs[$i]["COMMENTS"]}(审批时间：{$logs[$i]["ACTIONTIME"]})";
                else
                    $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：无 (审批时间：{$logs[$i]["ACTIONTIME"]})";
                $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
                $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:J{$h}");
            }


	        $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
   $objPHPExcel->getActiveSheet()->getStyle('A1:J'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
        



        	  $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
           ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=出差申请详情.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        
        $objWriter->save('php://output');
	}

	public function bumenchuchai($page=1,$list=10){
		$request = Request::instance();$data = $request->post();
		$state=Db::table("ti_state")->order("paixu")->select();

        $this->assign("state",$state);
		$eid=Session::get("employee_id");
		$u=Db::table("employee")->alias("e")
		->join("department_employee de","de.employee_id=e.id")
		->join("department d","de.department_id=d.id")
		->where("e.id=$eid and de.index=1")
		->field("d.id,d.de_name")
		->find();
		$where="ap.is_deleted=0 and d.id={$u["id"]} and de.index=1 ";
		if($data){
			if(trim($data["no"])){
				$no=trim($data["no"]);
				$where.="and ap.no='$no' ";
			}
			if(trim($data["title"])){
				$title=trim($data["title"]);
				$where.="and ap.title='$title' ";
			}
			if(trim($data["ttype"])){
				$ttype=trim($data["ttype"]);
				$where.="and ap.traveltype=$ttype ";
			}
			if(trim($data["daili"])){
				$daili=trim($data["daili"]);
				$where.="and e.em_name='$daili' ";
			}
			if(trim($data["st"])){
				$st=trim($data["st"]);
				$where.="and ap.state=$st ";
			}
			if(trim($data["start"])){
				$start=strtotime(trim($data["start"]));
				$where.="and ap.ctime>=$start ";
			}
			if(trim($data["end"])){
				$end=strtotime(trim($data["end"]));
				$where.="and ap.ctime<=$end ";
			}
		}else{
			$data=["no"=>"","title"=>"","ttype"=>"","daili"=>"","st"=>"","start"=>"","end"=>""];
		}
		$sum=Db::table("chuchai_apply")->alias("ap")
		->join("employee ce","ap.cuser=ce.id")
		->join("department_employee de","de.employee_id=ce.id")
		->join("department d","de.department_id=d.id")
		->join("employee e","ap.dailiren=e.id","LEFT")
       
		->where($where)
		->count();
		 $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $apply=Db::table("chuchai_apply")->alias("ap")
		->join("employee ce","ap.cuser=ce.id")
		->join("department_employee de","de.employee_id=ce.id")
		->join("department d","de.department_id=d.id")
		->join("employee e","ap.dailiren=e.id","LEFT")
		->join("ti_state s","ap.state=s.id")
       
		->where($where)->order("ap.id desc")->limit($start,$list)
		->field("ap.id,ap.no,ap.title,ap.state,s.title as statename,ap.traveltype,e.em_name,ap.ctime,ap.fankui")
		->select();
		for($i=0;$i<count($apply);$i++){
			$apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
      $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>5])->value("id");
		}
		$this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);
		return $this->fetch();
	}
	public function fankuichuli(){
		$request = Request::instance();$data = $request->post();
		if(strip_tags(trim($data["fankui"])))
			$updata["fankui"]=trim($data["fankui"]);
		else
			return json_encode(["msg"=>"反馈信息不能为空","state"=>2]);
		try{
			Db::table("chuchai_apply")->where(["id"=>$data["aid"]])->update($updata);
		}catch (\Exception $e){
       	
       		return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
       	}
		return json_encode(["msg"=>"","state"=>1]);
	}
	public function fankui($aid){
		$apply=Db::table("chuchai_apply")->where("id=$aid")->find();
			$this->assign("apply",$apply);
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);

			$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
			$daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
			$this->assign("daili",$daili);
          	$state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

          	$de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
          	$this->assign("de",$de);
          	$user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("ctime",$ctime);
        $this->assign("state",$state);
        $logs=$this->getlog(5,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
		return $this->fetch();
	}
	public function detail($aid){
		$apply=Db::table("chuchai_apply")->where("id=$aid")->find();
			$this->assign("apply",$apply);
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);

			$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
			$daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
			$this->assign("daili",$daili);
          	$state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

          	$de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
          	$this->assign("de",$de);
          	$user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("ctime",$ctime);
        $this->assign("state",$state);
        $logs=$this->getlog(5,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
		return $this->fetch();
	}

	public function shanchu($id){
		$res=Db::table("chuchai_apply")->where(["id"=>$id])->update(["is_deleted"=>1]);
		if($res)
			return 1;
		else
			return 0;
	}
	public function tijiao($id){
        $back=$this->gowork(5,$id);
        return $back;
		
	}
	public function mychuchai($page=1,$list=10){
		$request = Request::instance();$data = $request->post();
		$state=Db::table("ti_state")->order("paixu")->select();

        $this->assign("state",$state);
		$eid=Session::get("employee_id");
		$where="ap.is_deleted=0 and ap.cuser=$eid ";
		if($data){
			if(trim($data["no"])){
				$no=trim($data["no"]);
				$where.="and ap.no='$no' ";
			}
			if(trim($data["title"])){
				$title=trim($data["title"]);
				$where.="and ap.title='$title' ";
			}
			if(trim($data["ttype"])){
				$ttype=trim($data["ttype"]);
				$where.="and ap.traveltype=$ttype ";
			}
			if(trim($data["daili"])){
				$daili=trim($data["daili"]);
				$where.="and e.em_name='$daili' ";
			}
			if(trim($data["st"])){
				$st=trim($data["st"]);
				$where.="and ap.state=$st ";
			}
			if(trim($data["start"])){
				$start=strtotime(trim($data["start"]));
				$where.="and ap.ctime>=$start ";
			}
			if(trim($data["end"])){
				$end=strtotime(trim($data["end"]));
				$where.="and ap.ctime<=$end ";
			}
		}else{
			$data=["no"=>"","title"=>"","ttype"=>"","daili"=>"","st"=>"","start"=>"","end"=>""];
		}
		$sum=Db::table("chuchai_apply")->alias("ap")
		//->join("chuchai_detail apd","apd.aid=ap.id")
		->join("employee e","ap.dailiren=e.id","LEFT")
    
		->where($where)
		->count();
		 $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $apply=Db::table("chuchai_apply")->alias("ap")
		//->join("chuchai_detail apd","apd.aid=ap.id")
		->join("employee e","ap.dailiren=e.id","LEFT")
		->join("ti_state s","ap.state=s.id")
       
		->where($where)->order("ap.id desc")->limit($start,$list)
		->field("ap.id,ap.no,ap.title,ap.state,s.title as statename,ap.traveltype,e.em_name,ap.ctime,ap.fankui")
		->select();
		for($i=0;$i<count($apply);$i++){
			$apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
      $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>5])->value("id");
		}
		$this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);
		return $this->fetch();
	}

	public function add($aid=null){
		$this->assign("aid",$aid);
		if($aid){
			$apply=Db::table("chuchai_apply")->where("id=$aid")->find();
			$this->assign("apply",$apply);
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);

			$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
			$daili=Db::table("employee")->where(["id"=>$apply["dailiren"]])->find();
			$this->assign("daili",$daili);
          	$state=Db::table("ti_state")->where(["id"=>$apply["state"]])->value("title");

          	$de=Db::table("chuchai_detail")->where(["aid"=>$aid])->select();
          	$this->assign("de",$de);
		}else{
			//查询合同提交人信息
            $eid=Session::get("employee_id");
            $ctime=date("Y-m-d H:i:s");
          	$fujian=[];
          	$state="暂存";
		}
		  $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->join("users u","u.employee_id=em.id")
            ->join("users_role ur","u.id=ur.users_id")
            ->join("role r","ur.role_id=r.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id,r.role_name")
            ->find();
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("ctime",$ctime);
        $this->assign("state",$state);
		return $this->fetch();
	}
	public function addchuli(){
		$request = Request::instance();$data = $request->post();
       //print_r($data);exit;
       $adddata["state"]=$data["state"];
       $adddata["traveltype"]=$data["traveltype"];
       if(isset($data["baifang"]))
       		$adddata["baifang"]=implode(',', $data["baifang"]);
       	if($data["dailiren"])
       		$adddata["dailiren"]=$data["dailiren"];
       	if(trim($data["title"]))
       		$adddata["title"]=$data["title"];
       	else
       		return json_encode(["msg"=>"主题不能为空","state"=>2]);
       	if(trim($data["feiyong"]))
       		$adddata["feiyong"]=trim($data["feiyong"]);
       	else
       		$adddata["feiyong"]=0;
       	if(strip_tags(trim($data["target"])))
       		$adddata["target"]=trim($data["target"]);
       	else
       		return json_encode(["msg"=>"行程目的不能为空","state"=>2]);
       	$adddata["fujian"]=$data["attach"];
       	Db::startTrans();
       	try{
       		if($data["aid"]){
       			//修改
       			$adddata["puser"]=Session::get("employee_id");
       			$adddata["ptime"]=time();$aid=$data["aid"];
				$res1=Db::table("chuchai_apply")->where(["id"=>$aid])->update($adddata);
       			
       		}else{
       			//新增
       			 //生成单号
	            $timenow=date("Ymd");
	            $num=Db::table("chuchai_apply")->where("no like '$timenow%'")->count();
	            $num++;
	            $strnum=$timenow.sprintf("%05d", $num);
	            $adddata["no"]=$strnum;
	            $adddata["cuser"]=Session::get("employee_id");
	            $adddata["puser"]=Session::get("employee_id");
	            $adddata["ctime"]=time();
	            $adddata["ptime"]=time();
       			$res1=Db::table("chuchai_apply")->insertGetId($adddata);
       			$aid=$res1;
       		}

       	}catch (\Exception $e){
       		Db::rollBack();
       		if(!$data["aid"]){
       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
       		}
       		
       		return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
       	}
       	
       	$adddetail=[];
       	$reg_time="/^\d{2}:\d{2}$/";
       	try{
       		if(isset($data["start"])&&isset($data["end"])&&isset($data["chufa"])){
       			for($i=0;$i<count($data["start"]);$i++){
       				$tmp=[];
       				$tmp["aid"]=$aid;
       				if($data["start"][$i])
       					$tmp["start"]=$data["start"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细起始时间不能为空","state"=>2]);
       				}
       				if($data["end"][$i])
       					$tmp["end"]=$data["end"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细终止时间不能为空","state"=>2]);
       				}
       				if($data["chufa"][$i])
       					$tmp["chufa"]=$data["chufa"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细出发地不能为空","state"=>2]);
       				}
       				if($data["mudi"][$i])
       					$tmp["mudi"]=$data["mudi"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细目的地不能为空","state"=>2]);
       				}
       				if($data["ts"][$i])
       					$tmp["ts"]=$data["ts"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细天数不能为空或0","state"=>2]);
       				}
       				if($data["gl"][$i])
       					$tmp["gl"]=$data["gl"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细点对点公里数不能为空或0","state"=>2]);
       				}
       				if(preg_match($reg_time,trim($data["qishi"][$i])))
       					$tmp["qishi"]=trim($data["qishi"][$i]);
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细发车/起飞时间请按正确格式如：09:30","state"=>2]);
       				}
       				$tmp["fangshi"]=$data["fangshi"][$i];
       				if($data["shijian"][$i])
       					$tmp["shijian"]=$data["shijian"][$i];
       				else{
       					Db::rollBack();
			       		if(!$data["aid"]){
			       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
			       		}
       					return json_encode(["msg"=>"明细点对点乘车小时不能为空或0","state"=>2]);
       				}
       				if($data["peitongid"][$i])
       					$tmp["peitongid"]=$data["peitongid"][$i];
       				else
       					$tmp["peitongid"]=null;
       				if($data["peitongren"][$i])
       					$tmp["peitongren"]=$data["peitongren"][$i];
       				else
       					$tmp["peitongren"]=null;
       				$adddetail[]=$tmp;
       			}

       		}else{
       			Db::rollBack();
	       		if(!$data["aid"]){
	       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
	       		}
       			return json_encode(["msg"=>"请至少添加一条明细","state"=>2]);
       		}
       	}catch (\Exception $e){
       		Db::rollBack();
       		if(!$data["aid"]){
       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
       		}
       		return json_encode(["msg"=>"请正确提交","state"=>2]);
       	}
       	try{
       		Db::table("chuchai_detail")->where(["aid"=>$aid])->delete();
       		$res2=Db::table("chuchai_detail")->insertAll($adddetail);
       	}catch (\Exception $e){
       		Db::rollBack();
       		if(!$data["aid"]){
       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
       		}
       		return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
       	}
       	if($res1&&$res2){
            if($data["state"]==3){
                $back=$this->work(5,$aid);
                $backarr=json_decode($back,true);
                if($backarr["state"]!=1){
                    Db::rollBack();
                    return $back;
                }
            }

       		Db::commit();
       		return json_encode(["msg"=>"","state"=>1]);
       	}else{
       		Db::rollBack();
       		if(!$data["aid"]){
       			Db::table("chuchai_apply")->where(["id"=>$aid])->delete();
       		}
       		return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
       	}
	}
}